import type {Reactive, Ref} from "vue";
import type {SysUserReq} from "#/type/user";

export default function (
    fetchTableData: Function,
    treeSelectedKeys: Ref<(string | number)[]>,
    formSearch: Reactive<SysUserReq>,
    tablePagination: Reactive<any>
) {
    const formSearchSubmit = () => {
        const dept_id = (treeSelectedKeys.value || [] as (string | number)[]).join(',')
        let params: SysUserReq = {...tablePagination, ...formSearch, dept_id,}
        fetchTableData(params)
    }
    const formSearchReset = () => {
        // 重置表单数据
        const keys = Object.keys(formSearch) as (keyof SysUserReq)[]
        for (const key of keys) {
            formSearch[key] = undefined!
        }
        const dept_id = (treeSelectedKeys.value || [] as (string | number)[]).join(',')
        let params: SysUserReq = {...tablePagination, ...formSearch, dept_id}
        fetchTableData(params)
    }
    const formInputClear = (key: keyof SysUserReq, e: Event) => {
        if ((e.target as HTMLInputElement).value === '') {
            formSearch[key] = undefined!
            const dept_id = (treeSelectedKeys.value || [] as (string | number)[]).join(',')
            let params: SysUserReq = {...tablePagination, ...formSearch, dept_id}
            fetchTableData(params)
        }
    }
    const formSelectClear = (key: keyof SysUserReq, e: any) => {
        if (e === undefined || (Array.isArray(e) && e.length === 0)) {
            formSearch[key] = undefined!
            const dept_id = (treeSelectedKeys.value || [] as (string | number)[]).join(',')
            let params: SysUserReq = {...tablePagination, ...formSearch, dept_id}
            fetchTableData(params)
        }
    }

    const formDateRangeClear = (key: keyof SysUserReq, dates: [string, string], dateStrings: [string, string]) => {
        if (dates === null || dateStrings === null || (dateStrings[0] === '' || dateStrings[1] === '')) {
            formSearch[key] = undefined!
            const dept_id = (treeSelectedKeys.value || [] as (string | number)[]).join(',')
            let params: SysUserReq = {...tablePagination, ...formSearch, dept_id}
            fetchTableData(params)
        }
    }
    return {formSearchSubmit, formSearchReset, formInputClear, formSelectClear, formDateRangeClear}
}
